package com.axsoft.train;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.Toast;


/**
 * Route Activity class
 */
public class RouteActivity extends Activity implements OnClickListener, OnMultiChoiceClickListener {
	
	private boolean[] mSelections;
	
	private Resources mResources;
	
	private String mLastDirection;
	
	private ArrayList<String[]> mDirections;
	private ArrayList<String[]> mStations;
	
	private SharedPreferences mPreferences;
	
	/**
	 * Activity created
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.route);
	}
	
	
	/**
	 * Activity paused
	 */
	@Override
	public void onPause() {
		super.onPause();
		
		try {
			Editor editor = mPreferences.edit();
			editor.putInt("Direction", ((Spinner) findViewById(R.id.RouteDirectionSpinner)).getSelectedItemPosition());
			editor.putInt("From", ((Spinner) findViewById(R.id.RouteFromSpinner)).getSelectedItemPosition());
			editor.putInt("To", ((Spinner) findViewById(R.id.RouteToSpinner)).getSelectedItemPosition());
			editor.putBoolean("Nearest", ((CheckBox) findViewById(R.id.RouteNearestCheckBox)).isChecked());
			editor.putBoolean("Selection0", mSelections[0]);
			editor.putBoolean("Selection1", mSelections[1]);
			editor.putBoolean("Selection2", mSelections[2]);
			editor.putBoolean("Selection3", mSelections[3]);
			editor.putBoolean("Selection4", mSelections[4]);
			editor.commit();
		} catch (Exception e) {
			Log.e("RouteActivity.onPause", e.toString());
		}
	}
	
	
	/**
	 * Activity resumed
	 */
	@Override
	public void onResume() {
		super.onResume();
		
		try	{
			mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
			mResources = getResources();
			
			mSelections = new boolean[5];
			mSelections[0] = mPreferences.getBoolean("Selection0", true);
			mSelections[1] = mPreferences.getBoolean("Selection1", true);
			mSelections[2] = mPreferences.getBoolean("Selection2", true);
			mSelections[3] = mPreferences.getBoolean("Selection3", true);
			mSelections[4] = mPreferences.getBoolean("Selection4", true);
			
			initUi();
			
			((Spinner) findViewById(R.id.RouteDirectionSpinner)).setSelection(mPreferences.getInt("Direction", 0), true);
			((Spinner) findViewById(R.id.RouteFromSpinner)).setSelection(mPreferences.getInt("From", 0), true);
			((Spinner) findViewById(R.id.RouteToSpinner)).setSelection(mPreferences.getInt("To", 0), true);
			((CheckBox) findViewById(R.id.RouteNearestCheckBox)).setChecked(mPreferences.getBoolean("Nearest", false));
			
		} catch (Exception e)	{
			Log.e("RouteActivity.onResume", e.toString());
		}
	}
	
	/**
	 * Initializes UI (sets callbacks, etc)
	 */
	private void initUi() {
		final String region = mPreferences.getString("PrefRegion", Constants.DEFAULT_REGION);
		mDirections = CacheManager.getRawTextArray(this, region);
		mDirections = CacheManager.splitArrayList(mDirections);
		if (mDirections == null) {
			return;
		}
		
		// Fill the spinners
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mDirections.get(0));
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		Spinner directionSpinner = ((Spinner) findViewById(R.id.RouteDirectionSpinner));
		directionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() 
		{

			@Override
			public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
				try {
					mLastDirection = mDirections.get(1)[position];
					mStations = CacheManager.getRawTextArray(view.getContext(), mLastDirection);
					mStations = CacheManager.splitArrayList(mStations);
					
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(view.getContext(), android.R.layout.simple_spinner_item, mStations.get(1));
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					((Spinner) findViewById(R.id.RouteFromSpinner)).setAdapter(adapter);
					((Spinner) findViewById(R.id.RouteToSpinner)).setAdapter(adapter);
				} catch (Exception e) {
					Log.e("RouteActivity.directionSpinner.setOnItemSelectedListener", e.toString());
				}
			}

			@Override public void onNothingSelected(AdapterView<?> arg0) { }
			
		});
		directionSpinner.setAdapter(adapter);
		
		// Set Buttons Click listeners
		((Button) findViewById(R.id.RouteExpressButton)).setOnClickListener(new OnClickListener() {
			@Override 
			public void onClick(View v) { 
				showDialog(Constants.DIALOG_ID_EXPRESS); 
			}
		});
		((Button) findViewById(R.id.RouteInvertButton)).setOnClickListener(this);
		((Button) findViewById(R.id.RouteFindButton)).setOnClickListener(this);
	}
	
	
	/**
	 * Dialog Created
	 */
	@Override
	public Dialog onCreateDialog(int id) {
		if (id ==Constants.DIALOG_ID_EXPRESS) {
			return new AlertDialog.Builder(this).setTitle(getString(R.string.expresses_selection)).setMultiChoiceItems(
					mResources.getStringArray(R.array.express_variants), mSelections, this).setPositiveButton("OK", null).create();
		} else {
			return null; // TODO: null?
		}
	}
	
	
	/**
	 * Button Clicked
	 */
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
			case R.id.RouteInvertButton:
				// A lot of magic here =)
				int position = ((Spinner) findViewById(R.id.RouteFromSpinner)).getSelectedItemPosition();
				((Spinner) findViewById(R.id.RouteFromSpinner)).setSelection(((Spinner) findViewById(R.id.RouteToSpinner)).getSelectedItemPosition(), true);
				((Spinner) findViewById(R.id.RouteToSpinner)).setSelection(position, true);
				
				break;
				
			case R.id.RouteFindButton:
				try {
					String from = mStations.get(0)[((Spinner) findViewById(R.id.RouteFromSpinner)).getSelectedItemPosition()];
					String to = mStations.get(0)[((Spinner) findViewById(R.id.RouteToSpinner)).getSelectedItemPosition()];
					boolean nearest = ((CheckBox) findViewById(R.id.RouteNearestCheckBox)).isChecked();
					
					Constants.startScheduleActivity(this, mLastDirection, from, to, nearest, mSelections);
				
				} catch (Exception e) {
					Log.e("RouteActivity.onClick (FindButton)", e.toString());
				}
				
				break;
				
			default:
				break;
		}
	}
	
	
	/**
	 * Item in multiple choice checked
	 */
	@Override
	public void onClick(DialogInterface dialog, int which, boolean isChecked) {
		try {
			mSelections[which] = isChecked;
		} catch (Exception e)	{
			Log.e("RouteActivity.onClick (DialogInterface)", e.toString());
		}
	}
	
	
	/**
	 * Menu (HW) button was pressed
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.schedule_menu, menu);
	    return true;
	}
	
	
	/**
	 * Menu item selected
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.AddToFavorites: {
				try {
					String from = mStations.get(0)[((Spinner) findViewById(R.id.RouteFromSpinner)).getSelectedItemPosition()];
					String to = mStations.get(0)[((Spinner) findViewById(R.id.RouteToSpinner)).getSelectedItemPosition()];
					boolean nearest = ((CheckBox) findViewById(R.id.RouteNearestCheckBox)).isChecked();
					
					if (Constants.addToFavorites(this, from, to, mSelections, nearest)) {
						Toast.makeText(this, getString(R.string.favorite_added), Toast.LENGTH_LONG).show();
					} else {
						Toast.makeText(this, getString(R.string.error_occured), Toast.LENGTH_LONG).show();
					}
					
					return true;
				} catch (Exception e) {
					Log.e("RouteActivity.onOptionsItemSelected", e.toString());
					Toast.makeText(this, getString(R.string.error_occured), Toast.LENGTH_LONG).show();
					return false;
				}
			}
				
			default:
				return true;
		}
	}
	
}